package com.application.sistercityapplication.json;



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.text.Html;
import android.util.Log;

import com.application.sistercityapplication.dto.ContactDto;
import com.application.sistercityapplication.dto.DashBoardDto;
import com.application.sistercityapplication.dto.GalleryDto;
import com.application.sistercityapplication.dto.InformationDto;
import com.application.sistercityapplication.dto.InformationMasterDto;
import com.application.sistercityapplication.dto.KMSDto;
import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.dto.MouDto;
import com.application.sistercityapplication.dto.NewsDto;
import com.application.sistercityapplication.dto.PictureDto;
import com.application.sistercityapplication.dto.UserDto;
import com.application.sistercityapplication.main.R;
import com.application.sistercityapplication.model.Magazine;
import com.application.sistercityapplication.model.User;
import com.application.sistercityapplication.utils.GlobalVariable;

public class JSONParserForGetList {
	public Activity a;
	public String news_cat;
	private static JSONParserForGetList instance = null;
	private static HttpClient httpclient = null;
	// constructor
	protected JSONParserForGetList() {
	      // Exists only to defeat instantiation.
	}
	public static JSONParserForGetList getInstance() {
	      if(instance == null) {
	         instance = new JSONParserForGetList();
	      }
	      return instance;
	}
	public static HttpClient getClientInstance(){
		  if(httpclient == null) {
			  httpclient = new DefaultHttpClient();
		      }
		      return httpclient;
	}
	public JSONObject getLogout() {

		InputStream is = null;
		String result = "";
		JSONObject jObject = null;
		try {
			
			HttpClient httpclient = getClientInstance();
			HttpGet httppost = new HttpGet(GlobalVariable.URL_LOGOUT);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		return jObject;
	}
	

	public UserDto getLogin(String username, String password) {
		UserDto user = new UserDto();
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("username",username));
		nameValuePairs.add(new BasicNameValuePair("password",password));
		JSONObject json = getLoginfromURL(GlobalVariable.URL_LOGIN,nameValuePairs);
		boolean isPass = false;
		if (json != null) {
			try {
				if(json.getJSONObject("user") !=null){
					JSONObject usrJson =  json.getJSONObject("user"); 
					
					user.setId(usrJson.getString("id"));
					user.setUsername(usrJson.getString("username"));
					user.setFirstname(usrJson.getString("firstname"));
					user.setLastname(usrJson.getString("lastname"));
					user.setEmail(usrJson.getString("email"));
					user.setTelephone(usrJson.getString("telephone"));
					user.setStatus(true);
					
					
					user.setKey(json.getString("key"));

				
				}else{
					user.setStatus(false);
					user.setErrMsg((json.getString("message")));
				}
			}
			catch (Exception e) {
				try {
					user.setStatus(false);
					user.setErrMsg((json.getString("message")));
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
			}

		} else {
			user.setStatus(false);
			user.setErrMsg("System Fail");
		}
		return user;
	}
	
	public List<NewsDto> getNews(String countryId) {
		List<NewsDto> newsList = new ArrayList<NewsDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_NEWS+countryId,"news");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					NewsDto news = new NewsDto();
					JSONObject json_data = one.optJSONObject(i);
					news.setId(json_data.getString("id"));
					news.setTitle(json_data.getString("title"));
					news.setImage_path(json_data.getString("image_path"));
					news.setDescription(json_data.getString("description"));
					news.setCountry_id(json_data.getString("country_id"));
					news.setCreated_at(json_data.getString("updated_at"));
					news.setUpdated_at(json_data.getString("updated_at"));
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
					news.setCountry_name(country.getString("name"));
					}
					newsList.add(news);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return newsList;
	}
	public NewsDto getNewsDetail(String newsId) {
		NewsDto news = new NewsDto();
		JSONObject json_data = getJsonObjectFromUrlDoGet(GlobalVariable.URL_NEWSDETAIL+newsId,"news");
		if (json_data != null) {
			
			try {
					
					news.setId(json_data.getString("id"));
					news.setTitle(json_data.getString("title"));
					news.setImage_path(json_data.getString("image_path"));
					news.setDescription(stripHtml(json_data.getString("description")));
					news.setCountry_id(json_data.getString("country_id"));
					news.setCreated_at(json_data.getString("updated_at"));
					news.setUpdated_at(json_data.getString("updated_at"));
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
					news.setCountry_name(country.getString("name"));
					}
					JSONArray jArrGal = json_data.getJSONArray("gallery");
					if(jArrGal!=null){
						List<String> gallList = new ArrayList<String>();
						for(int i=0;i<jArrGal.length();i++){
							String imagepath = (String) jArrGal.get(0);
							gallList.add(imagepath);
						}
						news.setGallery(gallList);
					}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return news;
	}
	
	public List<MagazineDto> getMagazines(String countryId) {
		List<MagazineDto> magsList = new ArrayList<MagazineDto>();
		JSONArray json = null;
		if(!checkLogin()){
		json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_MAGAZINES+countryId,"magazines");
		}else{
			User user = new User();
			json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_MAGAZINES+countryId+"?key="+user.getKey(),"magazines");	
		}
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					MagazineDto mags = new MagazineDto();
					JSONObject json_data = one.optJSONObject(i);
					mags.setTitle(json_data.getString("title"));
					mags.setPath(json_data.getString("document_path"));
					mags.setTumbnail(json_data.getString("thumbnail"));
					mags.setCreated_at(json_data.getString("created_at"));
					mags.setUpdeted_at(json_data.getString("updated_at"));
					mags.setMagId(json_data.getString("id"));
					
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
						mags.setCat(country.getString("name"));
						mags.setCountryId(json_data.getString("country_id"));
					}
					JSONObject cat =  json_data.getJSONObject("category");
					if(cat!=null){
						mags.setCatId(cat.getString("id"));
					}
					magsList.add(mags);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return magsList;
	}
	
	public List<InformationMasterDto> getInformations(String countryId) {
		List<InformationMasterDto> magsList = new ArrayList<InformationMasterDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_INFORMATIONS+countryId,"informations");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					InformationMasterDto infoMaster = new InformationMasterDto();
					JSONObject json_data = one.optJSONObject(i);
					infoMaster.setCountryId(json_data.getString("country_id"));
					infoMaster.setId(json_data.getString("id"));
					infoMaster.setName(json_data.getString("name"));
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
						infoMaster.setCountryName(country.getString("name"));
						infoMaster.setCountryId(json_data.getString("country_id"));
					}
					infoMaster.setImageDrawable(R.drawable.sample_icon_list);
					List<InformationDto> infoList = new ArrayList<InformationDto>();
					JSONArray jaArray = json_data.getJSONArray("informations");
					for (int j = 0; j < jaArray.length(); j++) {
						JSONObject information = jaArray.optJSONObject(j);
						InformationDto mags = new InformationDto();
							mags.setCatId(information.getString("category_id"));
							mags.setTitle(information.getString("title"));
							mags.setPath(information.getString("document_path"));
							mags.setTumbnail(information.getString("thumbnail"));
							mags.setCreated_at(information.getString("created_at"));
							mags.setUpdeted_at(information.getString("updated_at"));
							mags.setMagId(information.getString("id"));
							infoList.add(mags);
						
					}
					infoMaster.setInformations(infoList);
					magsList.add(infoMaster);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return magsList;
	}
	public List<ContactDto> getContacts(String countryId) {
		List<ContactDto> conList = new ArrayList<ContactDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_CONTACT+countryId,"contacts");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					ContactDto contact = new ContactDto();
					JSONObject json_data = one.optJSONObject(i);
					contact.setTitle(json_data.getString("name"));
					contact.setPhone(json_data.getString("phone"));
					contact.setImagePath(json_data.getString("thumbnail"));
					contact.setDetail(json_data.getString("address"));
					
					conList.add(contact);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return conList;
	}
	
	public List<GalleryDto> getGallerys(String countryId) {
		List<GalleryDto> galList = new ArrayList<GalleryDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_GALLERY+countryId,"galleries");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {				
					GalleryDto galleryDto = new GalleryDto();
					JSONObject json_data = one.optJSONObject(i);
					galleryDto.setCatTitle(json_data.getString("title"));
					galleryDto.setCreated_at(json_data.getString("created_at"));
					
					JSONArray pictureArr = json_data.getJSONArray("picture");
					List<PictureDto> picList = new ArrayList<PictureDto>();
					for(int j = 0; j<pictureArr.length(); j++){
						JSONObject picture = pictureArr.optJSONObject(j);
						PictureDto pictureDto = new PictureDto();
						pictureDto.setPath(picture.getString("full"));
						pictureDto.setThumbnail(picture.getString("thumbnail"));
						picList.add(pictureDto);
					}
					galleryDto.setPictures(picList);
					galList.add(galleryDto);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return galList;
	}
	public List<MagazineDto> getKMS(String countryId) {
		List<MagazineDto> kmsList = new ArrayList<MagazineDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_KMS+countryId,"kms");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					MagazineDto kms = new MagazineDto();
					JSONObject json_data = one.optJSONObject(i);
					kms.setTitle(json_data.getString("title"));
					kms.setPath(json_data.getString("document_path"));
					kms.setTumbnail(json_data.getString("thumbnail"));
					kms.setCreated_at(json_data.getString("created_at"));
					kms.setUpdeted_at(json_data.getString("updated_at"));
					kms.setKmsId(json_data.getString("id"));
					
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
						kms.setCat(country.getString("name"));
						kms.setCountryId(json_data.getString("country_id"));
					}
					
					kmsList.add(kms);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return kmsList;
	}
	public List<MagazineDto> getMOU(String countryId) {
		List<MagazineDto> mouList = new ArrayList<MagazineDto>();
		JSONArray json = getJsonArrayFromUrlDoGet(GlobalVariable.URL_MOU+countryId,"MOU");
		if (json != null) {
			JSONArray one = json;
			try {
				for (int i = 0; i < one.length(); i++) {
					MagazineDto kms = new MagazineDto();
					JSONObject json_data = one.optJSONObject(i);
					kms.setTitle(json_data.getString("title"));
					kms.setPath(json_data.getString("document_path"));
					kms.setTumbnail(json_data.getString("thumbnail"));
					kms.setCreated_at(json_data.getString("created_at"));
					kms.setUpdeted_at(json_data.getString("updated_at"));
					kms.setMouId(json_data.getString("id"));
					
					JSONObject country =  json_data.getJSONObject("country");
					if(country!=null){
						kms.setCat(country.getString("name"));
						kms.setCountryId(json_data.getString("country_id"));
					}
					
					mouList.add(kms);
				}
				
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return mouList;
	}
	
	public DashBoardDto getDashBoard(String countryId) {
		DashBoardDto dashBoardDto = new DashBoardDto();
		JSONObject json = null;
		if(!checkLogin()){
			json = getJsonObjectFromUrlDoGet(GlobalVariable.URL_DASHBOARD+countryId,"informations");
		}else{
			User user = new User();
			json = getJsonObjectFromUrlDoGet(GlobalVariable.URL_DASHBOARD+countryId+"?key="+user.getKey(),"informations");	
		}
		if (json != null) {
			try {
				DashBoardDto dto = new DashBoardDto();
				JSONArray jArrayAbout = json.getJSONArray("about");
				if(jArrayAbout!=null && jArrayAbout.length()>0){
					JSONObject jsAbout = (JSONObject) jArrayAbout.get(0);
					dto.setDescription(stripHtml(jsAbout.getString("description")));
					dto.setFlag_path(jsAbout.getString("flag_path"));
				}
				JSONArray jArrayNews = json.getJSONArray("news");
				if(jArrayNews!=null && jArrayNews.length()>0){
					List<NewsDto> newList = new ArrayList<NewsDto>();
					for(int i=0;i<jArrayNews.length();i++){
						JSONObject jsNews = (JSONObject) jArrayNews.get(i);
						NewsDto newsDto = new NewsDto();
						newsDto.setTitle(jsNews.getString("title"));
						newsDto.setImage_path(jsNews.getString("image_path"));
						newsDto.setUpdated_at(jsNews.getString("updated_at"));
						newsDto.setId(jsNews.getString("id"));
						newList.add(newsDto);
					}
					dto.setNewsList(newList);
				}
				JSONArray jArrayMags = json.getJSONArray("magazines");
				if(jArrayMags!=null && jArrayMags.length()>0){
					List<MagazineDto> magList = new ArrayList<MagazineDto>();
					for(int i=0;i<jArrayMags.length();i++){
						JSONObject jsMag = (JSONObject) jArrayMags.get(i);
						MagazineDto magsDto = new MagazineDto();
						magsDto.setTitle(jsMag.getString("title"));
						magsDto.setTumbnail(jsMag.getString("thumbnail"));
						magsDto.setUpdeted_at(jsMag.getString("updated_at"));
						magsDto.setMagId(jsMag.getString("id"));
						magList.add(magsDto);
					}
					dto.setMagList(magList);
				}
				JSONArray jArrayKMSs = json.getJSONArray("kms");
				if(jArrayKMSs!=null && jArrayKMSs.length()>0){
					List<MagazineDto> kmsList = new ArrayList<MagazineDto>();
					for(int i=0;i<jArrayKMSs.length();i++){
						JSONObject jsKMS = (JSONObject) jArrayKMSs.get(i);
						MagazineDto kmsDto = new MagazineDto();
						kmsDto.setTitle(jsKMS.getString("title"));
						kmsDto.setTumbnail(jsKMS.getString("thumbnail"));
						kmsDto.setUpdeted_at(jsKMS.getString("updated_at"));
						kmsDto.setKmsId(jsKMS.getString("id"));
						kmsList.add(kmsDto);
					}
					dto.setKmsList(kmsList);
				}
				JSONArray jArrayMOUs = json.getJSONArray("MOU");
				if(jArrayMOUs!=null && jArrayMOUs.length()>0){
					List<MagazineDto> mouList = new ArrayList<MagazineDto>();
					for(int i=0;i<jArrayMOUs.length();i++){
						JSONObject jsKMS = (JSONObject) jArrayMOUs.get(i);
						MagazineDto mouDto = new MagazineDto();
						mouDto.setTitle(jsKMS.getString("title"));
						mouDto.setTumbnail(jsKMS.getString("thumbnail"));
						mouDto.setUpdeted_at(jsKMS.getString("updated_at"));
						mouDto.setMouId(jsKMS.getString("id"));
						mouList.add(mouDto);
					}
					dto.setMouList(mouList);
				}
				dashBoardDto = dto;
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
		return dashBoardDto;
	}
	
	
	
	public JSONObject getLoginfromURL(String url,
			List<NameValuePair> nameValuePairs) {

		InputStream is = null;
		String result = "";
		JSONObject jObject = null;
		try {
			
			HttpClient httpclient = getClientInstance();
			HttpPost httppost = new HttpPost(url);

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
				// System.out.println("Show Result::::"+line);
			}
			is.close();
			result = sb.toString();
			jObject = new JSONObject(result);
			
	
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		return jObject;
	}
	
	
	

	public JSONArray getJsonArrayFromUrlDoGet(String url,String jsonArray) {

		InputStream is = null;
		String result = "";
		JSONArray jArray = null;
		JSONObject jObject = null;
		try {
			HttpClient httpclient = getClientInstance();
			HttpGet httppost = new HttpGet(url);

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
				// System.out.println("Show Result::::"+line);
			}
			is.close();
			result = sb.toString();
			jObject = new JSONObject(result);
			
	
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			jArray = jObject.getJSONArray(jsonArray);
		} catch (Exception e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return jArray;
	}
	public JSONObject getJsonObjectFromUrlDoGet(String url,String jsonObject) {

		InputStream is = null;
		String result = "";
		JSONObject jObject = null;
		JSONObject jo = null;
		try {
			HttpClient httpclient = getClientInstance();
			HttpGet httppost = new HttpGet(url);

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
				// System.out.println("Show Result::::"+line);
			}
			is.close();
			result = sb.toString();
			jObject = new JSONObject(result);
			
	
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			jo = jObject.getJSONObject(jsonObject);
		} catch (Exception e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return jo;
	}


	public String getImageSrc(String s){
		String word0= "";
		if(s != null && !"".equals(s)){
		Pattern p=null;
		Matcher m= null;
		
		String word1= null;
		p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
		m = p.matcher(s);
		if (m.find()) {
			word0 = m.group(1);
		}
		}
		return word0;
	}
	
	public long getDiffDay(Date d){
		 long diffDays = 0L;
		if(d!=null){
			Calendar calendar1 = Calendar.getInstance();
		    Calendar calendar2 = Calendar.getInstance();
		    calendar1.set(calendar1.get(Calendar.YEAR), d.getMonth(), d.getDate());
		    long milliseconds1 = calendar1.getTimeInMillis();
		    long milliseconds2 = calendar2.getTimeInMillis();
		    long diff = milliseconds2 - milliseconds1;
		    diffDays = diff / (24 * 60 * 60 * 1000);
		}
		return diffDays;
	}
	
	public String stripHtml(String html) {
	    return Html.fromHtml(html).toString();
	}
	public boolean checkLogin() {
		User user = new User();
		return user.isNotEmpty();
	}
	
}